package com.example.landrentpaymentbackend.service;

import com.example.landrentpaymentbackend.dto.ImportResult;
import com.example.landrentpaymentbackend.entity.RentRecord;
import com.example.landrentpaymentbackend.mapper.RentRecordMapper;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class ExcelImportService {

    private final RentRecordMapper rentRecordMapper;

    @Transactional(rollbackFor = Exception.class)
    public ImportResult importExcel(MultipartFile file) throws IOException {
        ImportResult result = new ImportResult();

        try (Workbook wb = WorkbookFactory.create(file.getInputStream())) {
            Sheet sheet = wb.getSheetAt(0);
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                try {
                    RentRecord r = new RentRecord();
                    r.setTaiAccount(stringCell(row, 0));
                    r.setCrop(stringCell(row, 1));
                    r.setName(stringCell(row, 2));
                    r.setPhone(stringCell(row, 3));
                    r.setArea(decimalCell(row, 4));
                    r.setFeeStandard(stringCell(row, 5));
                    r.setUnitPrice(decimalCell(row, 6));
                    r.setRentDue(decimalCell(row, 7));
                    r.setIdCard(stringCell(row, 8));
                    r.setStartEndDate(stringCell(row, 9));
                    r.setContractNo(stringCell(row, 10));
                    r.setBreach(stringCell(row, 11));
                    r.setQueue(stringCell(row, 12));
                    r.setPayYear(stringCell(row, 13));
                    r.setPlotNo(stringCell(row, 14));
                    r.setStatus("UNPAID");

                    rentRecordMapper.insert(r);
                    result.incrSuccess();
                } catch (Exception e) {
                    result.addFail("第 " + (i + 1) + " 行：" + e.getMessage());
                }
            }
        }
        return result;
    }

    /* ===== 读取单元格 ===== */
    private String stringCell(Row row, int col) {
        Cell cell = row.getCell(col);
        if (cell == null) return "";
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }

    private BigDecimal decimalCell(Row row, int col) {
        try {
            String val = stringCell(row, col);
            return new BigDecimal(val);
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }
}